import { throttle } from '../../utils';
import React, { ChangeEvent, useState } from 'react';
import './index.less';

interface ISearchProps {
    placeholder: string;
    onChange: (
        event: ChangeEvent<HTMLInputElement>,
        showData: IShowDataItem[],
        setShowData: React.Dispatch<React.SetStateAction<IShowDataItem[]>>,
    ) => void;
}

interface IShowDataItem {
    id: string;
    content: string;
}

export default function Search(props: ISearchProps) {
    const [showData, setShowData] = useState<IShowDataItem[]>([]);

    const changeFn = ((showData, setShowData) => {
        return throttle((event: ChangeEvent<HTMLInputElement>) => props.onChange(event, showData, setShowData), 400);
    })(showData, setShowData);

    return (
        <>
            <div className="search">
                <input type="text" className="search-box" placeholder={props.placeholder} onChange={changeFn} />
                <ul className="search-result">
                    {showData.map((item) => (
                        <li key={item.id}>{item.content}</li>
                    ))}
                </ul>
            </div>
        </>
    );
}
